package org.gol.paxos.member;

import org.gol.paxos.Message;
import org.gol.paxos.client.PaxosIslandBasic;
import org.gol.paxos.role.Acceptor;
import org.gol.paxos.role.MessageTranser;
import org.gol.paxos.role.Proposer;

/**
 * @package org.gol.paxos.client.member
 * @description 【侍从】在参议员与公民代表间传递信息
 * @author Goliath
 * @createTime 2012-11-21 下午1:32:42
 * @modifyTime
 */
public class Servent implements MessageTranser {
	/**
	 * 侍从的可靠性
	 */
	public static int reliability = 100;

	@Override
	public void transMessage(Message oMessage) {
		try {
			// 传递消息话费的时间
			Thread.sleep((int) (Math.random() * 100));
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		if (Math.random() * 100 < reliability) {
			if ("prepare".equals(oMessage.getCommand()) || "publish".equals(oMessage.getCommand())
					|| "confirm".equals(oMessage.getCommand())) {
				Acceptor oAcceptor = PaxosIslandBasic.oParliament.acceptorPositions.get(oMessage.getSendTo());
				if (oAcceptor != null) {
					try {
						oAcceptor.getMessageQueue().put(oMessage);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				} else {
					System.out.println("没有找到收信人" + oMessage.getSendTo() + ",此信息来自" + oMessage.getFrom() + ",命令为"
							+ oMessage.getCommand());
				}
			} else if ("agree".equals(oMessage.getCommand()) || "disagree".equals(oMessage.getCommand())) {
				Proposer oProposer = PaxosIslandBasic.oParliament.proposerPositions.get(oMessage.getSendTo());
				if (oProposer != null) {
					try {
						oProposer.getMessageQueue().put(oMessage);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				} else {
					System.out.println("没有找到收信人" + oMessage.getSendTo() + ",此信息来自" + oMessage.getFrom() + ",命令为"
							+ oMessage.getCommand());
				}
			} else {
				System.out.println("侍从不能明白命令的含义,命令为:" + oMessage.getCommand());
			}
		} else {
			System.out.println("侍从偷懒了，没有送达消息,消息内容:" + oMessage.getContent());
		}
	}

}
